using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
//
// DotNetNuke?- http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
// 

using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;
using Telerik.Web.UI;

namespace DotNetNuke.HtmlEditor.TelerikEditorProvider.Dialogs
{

	/// <summary>
	/// 
	/// </summary>
	/// <remarks>
	/// </remarks>
	/// <history>
	/// </history>
	partial class SaveTemplate : DotNetNuke.Framework.PageBase
	{

		#region "Event Handlers"

		protected void Page_Init(object sender, System.EventArgs e)
		{
			if (Request.IsAuthenticated == true) {
				Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
			}

			ManageStyleSheets(false);
			ManageStyleSheets(true);
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			try {
				SetResStrings();
				if (!IsPostBack) {
					int portalID = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId;
					ArrayList folders = DotNetNuke.Common.Utilities.FileSystemUtils.GetFoldersByUser(portalID, true, true, "ADD");

					if (folders.Count == 0) {
						msgError.InnerHtml = GetString("msgNoFolders.Text");
						divInputArea.Visible = false;
						cmdClose.Visible = true;
					} else {
						FolderList.Items.Clear();

                        FolderList.DataTextField = "DisplayPath";
						FolderList.DataValueField = "FolderPath";
						FolderList.DataSource = folders;
						FolderList.DataBind();

						RadComboBoxItem rootFolder = FolderList.FindItemByText(string.Empty);
						if (rootFolder != null) {
							rootFolder.Text = GetString("lblRootFolder.Text");
						}
					}
				}
			} catch (Exception ex) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				throw ex;
			}
		}

		protected void Save_OnClick(object sender, EventArgs e)
		{
			try {
				if (FolderList.Items.Count == 0) {
					return;
				}

				DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current;

				string fileContents = htmlText2.Text.Trim();
				string newFileName = FileName.Text;
				if (!newFileName.EndsWith(".htmtemplate")) {
					newFileName = newFileName + ".htmtemplate";
				}

				string rootFolder = portalSettings.HomeDirectoryMapPath;
				string dbFolderPath = FolderList.SelectedValue;
				string virtualFolder = FileSystemValidation.ToVirtualPath(dbFolderPath);
				rootFolder = rootFolder + FolderList.SelectedValue;
				rootFolder = rootFolder.Replace("/", "\\");

				string errorMessage = string.Empty;
				FolderController folderCtrl = new FolderController();
				FolderInfo folder = folderCtrl.GetFolder(portalSettings.PortalId, dbFolderPath, false);

				if (((folder == null))) {
					ShowSaveTemplateMessage(GetString("msgFolderDoesNotExist.Text"));
					return;
				}

				// Check file name is valid
				FileSystemValidation dnnValidator = new FileSystemValidation();
				errorMessage = dnnValidator.OnCreateFile(virtualFolder + newFileName, fileContents.Length);
				if ((!string.IsNullOrEmpty(errorMessage))) {
					ShowSaveTemplateMessage(errorMessage);
					return;
				}

				FileController fileCtrl = new FileController();
				DotNetNuke.Services.FileSystem.FileInfo existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID);

				// error if file exists
				if ((!Overwrite.Checked && (existingFile != null))) {
					ShowSaveTemplateMessage(GetString("msgFileExists.Text"));
					return;
				}

				FileInfo newFile = existingFile;
				if (((newFile == null))) {
					newFile = new FileInfo();
				}

				newFile.FileName = newFileName;
				newFile.ContentType = "text/plain";
				newFile.Extension = "htmtemplate";
				newFile.Size = fileContents.Length;
				newFile.FolderId = folder.FolderID;

				errorMessage = DotNetNuke.Common.Utilities.FileSystemUtils.CreateFileFromString(rootFolder, newFile.FileName, fileContents, newFile.ContentType, string.Empty, false);

				if ((!string.IsNullOrEmpty(errorMessage))) {
					ShowSaveTemplateMessage(errorMessage);
					return;
				}

				existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID);
				if ((newFile.FileId != existingFile.FileId)) {
					newFile.FileId = existingFile.FileId;
				}

				if ((newFile.FileId != Null.NullInteger)) {
                    fileCtrl.UpdateFile(newFile);
				} else {
                    fileCtrl.AddFile(newFile);
				}

				ShowSaveTemplateMessage(string.Empty);
			} catch (Exception ex) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				throw ex;
			}
		}

		#endregion

		#region "Properties"

		#endregion

		#region "Methods"

		private void ShowSaveTemplateMessage(string errorMessage)
		{
			if (errorMessage == string.Empty) {
				msgSuccess.Visible = true;
				msgError.Visible = false;
			} else {
				msgSuccess.Visible = false;
				msgError.Visible = true;
				msgError.InnerHtml += errorMessage;
				DotNetNuke.Services.Exceptions.Exceptions.LogException(new FileManagerException("Error creating htmtemplate file [" + errorMessage + "]"));
			}

			divInputArea.Visible = false;
			cmdClose.Visible = true;
		}

		private void SetResStrings()
		{
			lblFolders.Text = GetString("lblFolders.Text");
			lblFileName.Text = GetString("lblFileName.Text");
			lblOverwrite.Text = GetString("lblOverwrite.Text");
			cmdSave.Text = GetString("cmdSave.Text");
			cmdCancel.Text = GetString("cmdCancel.Text");
			cmdClose.Text = GetString("cmdClose.Text");
			msgSuccess.InnerHtml = GetString("msgSuccess.Text");
			msgError.InnerHtml = GetString("msgError.Text");
		}

		protected string GetString(string key)
		{
			string resourceFile = System.IO.Path.Combine(this.TemplateSourceDirectory + "/", DotNetNuke.Services.Localization.Localization.LocalResourceDirectory + "/SaveTemplate.resx");
			return DotNetNuke.Services.Localization.Localization.GetString(key, resourceFile);
		}


		private void ManageStyleSheets(bool PortalCSS)
		{
			// initialize reference paths to load the cascading style sheets
			string ID = null;

			Hashtable objCSSCache = (Hashtable)DotNetNuke.Common.Utilities.DataCache.GetCache("CSS");
			if (objCSSCache == null) {
				objCSSCache = new Hashtable();
			}

			if (PortalCSS == false) {
				// default style sheet ( required )
				ID = Globals.CreateValidID(DotNetNuke.Common.Globals.HostPath);
				AddStyleSheet(ID, DotNetNuke.Common.Globals.HostPath + "default.css");

				// skin package style sheet
				ID = Globals.CreateValidID(PortalSettings.ActiveTab.SkinPath);
				if (objCSSCache.ContainsKey(ID) == false) {
					if (System.IO.File.Exists(Server.MapPath(PortalSettings.ActiveTab.SkinPath) + "skin.css")) {
						objCSSCache[ID] = PortalSettings.ActiveTab.SkinPath + "skin.css";
					} else {
						objCSSCache[ID] = "";
					}
					if (DotNetNuke.Entities.Host.Host.PerformanceSetting != DotNetNuke.Common.Globals.PerformanceSettings.NoCaching)
					{
						DotNetNuke.Common.Utilities.DataCache.SetCache("CSS", objCSSCache);
					}
				}
				if (!string.IsNullOrEmpty(objCSSCache[ID].ToString())) {
					AddStyleSheet(ID, objCSSCache[ID].ToString());
				}

				// skin file style sheet
				ID = Globals.CreateValidID(PortalSettings.ActiveTab.SkinSrc.Replace(".ascx", ".css"));
				if (objCSSCache.ContainsKey(ID) == false) {
					if (System.IO.File.Exists(Server.MapPath(PortalSettings.ActiveTab.SkinSrc.Replace(".ascx", ".css")))) {
						objCSSCache[ID] = PortalSettings.ActiveTab.SkinSrc.Replace(".ascx", ".css");
					} else {
						objCSSCache[ID] = "";
					}
					if (DotNetNuke.Entities.Host.Host.PerformanceSetting != DotNetNuke.Common.Globals.PerformanceSettings.NoCaching)
					{
						DotNetNuke.Common.Utilities.DataCache.SetCache("CSS", objCSSCache);
					}
				}
				if (!string.IsNullOrEmpty(objCSSCache[ID].ToString())) {
					AddStyleSheet(ID, objCSSCache[ID].ToString());
				}
			} else {
				// portal style sheet
				ID = DotNetNuke.Common.Globals.CreateValidID(PortalSettings.HomeDirectory);
				AddStyleSheet(ID, PortalSettings.HomeDirectory + "portal.css");
			}
		}


		public void AddStyleSheet(string id, string href, bool isFirst)
		{
			//Find the placeholder control
			Control objCSS = this.FindControl("CSS");

			if ((objCSS != null)) {
				//First see if we have already added the <LINK> control
				Control objCtrl = Page.Header.FindControl(id);

				if (objCtrl == null) {
					HtmlLink objLink = new HtmlLink();
					objLink.ID = id;
					objLink.Attributes["rel"] = "stylesheet";
					objLink.Attributes["type"] = "text/css";
					objLink.Href = href;

					if (isFirst) {
						//Find the first HtmlLink
						int iLink = 0;
						for (iLink = 0; iLink <= objCSS.Controls.Count - 1; iLink++) {
							if (objCSS.Controls[iLink] is HtmlLink) {
								break; 
							}
						}
						objCSS.Controls.AddAt(iLink, objLink);
					} else {
						objCSS.Controls.Add(objLink);
					}
				}
			}

		}

		public void AddStyleSheet(string id, string href)
		{
			AddStyleSheet(id, href, false);
		}
		public SaveTemplate()
		{
			Load += Page_Load;
			Init += Page_Init;
		}

		#endregion

	}

}
